import { Login, Logout } from "@/api/login";
import { setToken, getToken, removeToken, setUserName, getUserName, removeUserName } from "@/utils/app";

const state = {
  roles: [],
  isCollapse: JSON.parse(sessionStorage.getItem("isCollapse")) || false,
  admin_token: getToken() || "",
  username: getUserName() || "",
  btnPerm: []
};
const getters = {
  roles: state => state.roles
  //  btnPerm: state => state.btnPerm,
};
const mutations = { // 必须 同步没有回调处理
  SET_COLLAPSE: (state => {
    state.isCollapse = !state.isCollapse;
    // html5 本地存储
    sessionStorage.setItem("isCollapse", JSON.stringify(state.isCollapse));
  }),
  SET_TOKEN(state, value) {
    state.admin_token = value;
  },
  SET_USERNAME(state, value) {
    state.username = value;
  },
  SET_ROLES(state, value) {
    state.roles = value;
  },
  SET_BUTTON(state, value) {
    state.btnPerm = value;
  }
};
const actions = { // 可以有回调
  // 登录
  login(content, requestData) {
    return new Promise((resolve, reject) => {
      Login(requestData).then(res => {
        let data = res.data.data;
        content.commit("SET_TOKEN", data.token);
        content.commit("SET_USERNAME", data.username);
        setToken(data.token);
        setUserName(data.username);
        resolve(res);
      }).catch(error => {
        reject(error);
      });
    });
  },
  // 退出登录 { commit } 解构
  exit({ commit }) {
    return new Promise((resolve, reject) => {
      Logout().then(res => {
        let redData = res.data;
        removeToken();
        removeUserName();
        commit("SET_TOKEN", "");
        commit("SET_USERNAME", "");
        commit("SET_ROLES", []);
        resolve(redData);
      });

    });
  }
};
export default {
  namespaced: true, // 解决命名空间问题
  state,
  getters,
  mutations,
  actions
};
